import json
from os import name
from typing import List

from sqlalchemy.orm import Session
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
from app.schemas.user import UserCreate, UserResponse
from app.models.user import User
from app.core.encryption_utils import cipher
from app.repositories.user_repository import UserRepository  # 新增Repository导入
from app.core.local_logging import setup_logging

logger = setup_logging()

class UserService:
    """用户业务逻辑层（类似Java Service）"""
    
    def __init__(self, db: Session):
        self.db = db
        self.repository = UserRepository(db)  # 注入Repository

    def authenticate(self, username: str, password: str) -> bool:
        """认证用户（业务逻辑）"""
        try:
            user = self.repository.get_by_username(username)
            logger.debug(f"尝试登录用户: {user.__dict__}")
            return user and password == cipher.decrypt(user.password)  # 加密后比对
        except SQLAlchemyError as e:
            logger.error(f"认证失败: {str(e)}")
            return False

    def create_user(self, user_create: UserCreate) -> UserResponse | None:
        """创建用户（业务逻辑）"""
        logger.info(f"开始创建用户: {user_create.username, user_create.password}")
        try:
            # 检查用户是否存在（业务逻辑）
            if self.repository.get_by_username(user_create.username):
                logger.warning(f"用户名已存在: {user_create.username}")
                return None
            
            # 加密密码（业务逻辑）
            encrypted_pwd = cipher.encrypt(user_create.password)
            new_user = User(username=user_create.username, password=encrypted_pwd)
            
            # 调用Repository保存（纯数据操作）
            saved_user = self.repository.save(new_user)
            logger.info(f"用户创建成功: {saved_user.__dict__}")
            logger.info(f"用户创建成功: {UserResponse.model_validate(saved_user)}")
            return UserResponse.model_validate(saved_user)  # 转换为DTO返回
        except IntegrityError:
            self.db.rollback()
            logger.error("数据库唯一约束冲突")
            return None
        except SQLAlchemyError as e:
            self.db.rollback()
            logger.error(f"创建用户失败: {str(e)}")
            return None

    def delete_user(self, username: str) -> bool:
        """删除用户（业务逻辑）"""
        try:
            return self.repository.delete(username)  # 调用Repository删除
        except SQLAlchemyError as e:
            self.db.rollback()
            logger.error(f"删除用户失败: {str(e)}")
            return False

    def get_all_users(self) -> List[UserResponse] | None:
        """获取所有用户（业务逻辑）"""
        try:
            users = self.repository.get_all()  # 调用Repository查询
            if not users:
                return []
            result = []
            for user in users:
                logger.debug(f"用户: {user.__dict__}")
                user_info = UserResponse.model_validate(user)
                result.append(user_info)
            print(json.dumps(
                result
            ))
            return result
        except SQLAlchemyError as e:
            logger.error(f"查询用户列表失败: {str(e)}")
            return []